package com.by_man.presenter.module_health_records.access_records;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.repository.IpAddress;
import com.by_man.repository.PostStringRequest;
import com.by_man.repository.UserInfos;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by man on 2017-03-17.
 */
public class AddMedicationActivity extends AppCompatActivity {
    private int year, monthOfYear, dayOfMonth, hourOfDay, minute;
    private Switch openSwitch;
    private String state="0";
    int n = 3;
    private EditText amountView;
    private EditText nameView;
    private TextView tv1, tv2, tv3, tv4, tv5, tvx;
    private RequestQueue rQueue;

    private Handler handler;

    private final static int ADD_SUCCESS = 0x1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_medication);
        //rQueue = Volley.newRequestQueue(this);
        rQueue = SharedApplication.getrQueue(getApplication());
        rQueue.start();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ADD_SUCCESS:
                        Toast.makeText(AddMedicationActivity.this,"添加成功!",Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(AddMedicationActivity.this, MedicationRecordActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
            }
        };
        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                Intent intent = new Intent(this, MedicationRecordActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);
                onBackPressed();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(this, MedicationRecordActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            startActivity(intent);
//        }
//        return super.onKeyDown(keyCode,event);
//    }

//    protected void onRestart()
//    {
//        super.onRestart();
//        Intent intent=new Intent(this,GestureLockActivity.class);
//        intent.putExtra("class",this.getClass().getName());
//        intent.putExtra("position", 0);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
//    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        //toolbar.setTitle("时间列表");
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        final EditText startView = (EditText) findViewById(R.id.start);
        final EditText typeView = (EditText) findViewById(R.id.type);
        final EditText endView = (EditText) findViewById(R.id.end);
        openSwitch= (Switch) findViewById(R.id.open);
        tv1 = (TextView) findViewById(R.id.medinice_nl_time1);
        tv2 = (TextView) findViewById(R.id.medinice_nl_time2);
        tv3 = (TextView) findViewById(R.id.medinice_nl_time3);
        tv4 = (TextView) findViewById(R.id.medinice_nl_time4);
        tv5 = (TextView) findViewById(R.id.medinice_nl_time5);
        //每天3次
        tvx = (TextView) findViewById(R.id.rate);
        nameView = (EditText) findViewById(R.id.name);
        amountView = (EditText) findViewById(R.id.amount);

        final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
        final Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        monthOfYear = calendar.get(Calendar.MONTH);
        dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
        minute = calendar.get(Calendar.MINUTE);

        startView.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
        startView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(AddMedicationActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        startView.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                }, year, monthOfYear, dayOfMonth);
                datePickerDialog.show();
            }
        });

        startView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    DatePickerDialog datePickerDialog = new DatePickerDialog(AddMedicationActivity.this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            startView.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                        }
                    }, year, monthOfYear, dayOfMonth);
                    datePickerDialog.show();
                }
            }
        });


        // endView.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
        endView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(AddMedicationActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        endView.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                }, year, monthOfYear, dayOfMonth);
                datePickerDialog.show();
            }
        });
        endView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    DatePickerDialog datePickerDialog = new DatePickerDialog(AddMedicationActivity.this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            endView.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                        }
                    }, year, monthOfYear, dayOfMonth);
                    datePickerDialog.show();
                }
            }
        });

        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TimePickerDialog timePickerDialog = new TimePickerDialog(AddMedicationActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv1.setText(hourOfDay + ":" + minute);
                    }
                }, hourOfDay, minute, true);



                timePickerDialog.show();
            }
        });
        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TimePickerDialog timePickerDialog = new TimePickerDialog(AddMedicationActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv2.setText(hourOfDay + ":" + minute);
                    }
                }, hourOfDay, minute, true);

                timePickerDialog.show();
            }
        });
        tv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TimePickerDialog timePickerDialog = new TimePickerDialog(AddMedicationActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv3.setText(hourOfDay + ":" + minute);
                    }
                }, hourOfDay, minute, true);

                timePickerDialog.show();
            }
        });
        tv4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TimePickerDialog timePickerDialog = new TimePickerDialog(AddMedicationActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv4.setText(hourOfDay + ":" + minute);
                    }
                }, hourOfDay, minute, true);

                timePickerDialog.show();
            }
        });
        tv5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TimePickerDialog timePickerDialog = new TimePickerDialog(AddMedicationActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv5.setText(hourOfDay + ":" + minute);
                    }
                }, hourOfDay, minute, true);
                timePickerDialog.show();
            }
        });

        Button button_plus = (Button) findViewById(R.id.medinice_add);
        addandreduce(Integer.parseInt(tvx.getText().toString()));
        button_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (n >= 1 && n < 5) {
                    n = n + 1;
                    addandreduce(n);
                    tvx.setText(n + "");
                }
            }
        });

        Button button_reduce = (Button) findViewById(R.id.medinice_reduce);
        button_reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (n > 1 && n <= 5) {
                    n = n - 1;
                    addandreduce(n);
                    tvx.setText(n + "");
                }
            }
        });
        openSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    state = "2";     //长期用药

                } else {
                    state = "0";     //短期用药
                }
            }
        });

        Button buttton_save = (Button) findViewById(R.id.themedinice_add_save);
        buttton_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String drugname = nameView.getText().toString().trim();
                String drugtype = typeView.getText().toString().trim();
                String drugrate = tvx.getText().toString().trim();       //每天几次
                String drugamout1 = amountView.getText().toString().trim();  //每次几片
                String drugamout = drugamout1;
                String drugstart = startView.getText().toString().trim();
                String drugsend = endView.getText().toString().trim();

                if (drugname.equals("") || drugtype.equals("") || drugamout.equals("") || drugstart.equals("")) {
                    Toast.makeText(AddMedicationActivity.this, "有项目为空", Toast.LENGTH_SHORT).show();
                } else {
                    List<Map<String, Object>> testlist = new ArrayList<Map<String, Object>>();
                    Map<String, Object> test1 = new HashMap<String, Object>();
                    test1.put("drugname", drugname);
                    test1.put("drugtype", drugtype);
                    test1.put("drugrate", drugrate);
                    test1.put("drugdosage", drugamout);
                    test1.put("drugstart", drugstart);
                    test1.put("drugsend", drugsend);
                    test1.put("state", state);
                    testlist.add(test1);
                    Gson gson = new Gson();
                    String dataString = gson.toJson(testlist).toString();

                    HashMap<String,String> params = new HashMap<String, String>();
                    params.put("token", UserInfos.token);
                    params.put("json", dataString);

                    PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST,
                            IpAddress.Add_Medication, params,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String s) {
                                    Message msg = handler.obtainMessage();
                                    msg.what = ADD_SUCCESS;
                                    msg.sendToTarget();
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {
                                    Log.e("AddMedicationError", volleyError.getMessage(),volleyError);
                                }
                            });
                    rQueue.add(stringRequest);
                }
            }
        });
    }

    private void addandreduce(int n)
    {
        switch (n) {
            case 1:
                tv1.setVisibility(View.VISIBLE);
                tv2.setVisibility(View.GONE);
                tv3.setVisibility(View.GONE);
                tv4.setVisibility(View.GONE);
                tv5.setVisibility(View.GONE);
                break;
            case 2:
                tv1.setVisibility(View.VISIBLE);
                tv2.setVisibility(View.VISIBLE);
                tv3.setVisibility(View.GONE);
                tv4.setVisibility(View.GONE);
                tv5.setVisibility(View.GONE);
                break;
            case 3:
                tv1.setVisibility(View.VISIBLE);
                tv2.setVisibility(View.VISIBLE);
                tv3.setVisibility(View.VISIBLE);
                tv4.setVisibility(View.GONE);
                tv5.setVisibility(View.GONE);
                break;
            case 4:
                tv1.setVisibility(View.VISIBLE);
                tv2.setVisibility(View.VISIBLE);
                tv3.setVisibility(View.VISIBLE);
                tv4.setVisibility(View.VISIBLE);
                tv5.setVisibility(View.GONE);
                break;
            case 5:
                tv1.setVisibility(View.VISIBLE);
                tv2.setVisibility(View.VISIBLE);
                tv3.setVisibility(View.VISIBLE);
                tv4.setVisibility(View.VISIBLE);
                tv5.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }
}
